package com.winning.common.tools;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.framework.FrameworkServlet;
import com.winning.common.Constans;
import com.winning.common.xmlSchema.ICDASchemaValidatorInter;
import com.winning.common.xmlSchema.SchemaSummary;
import com.winning.common.xmlSchema.schema.CDASchemaSAXValidator;
import com.winning.common.xmlSchema.schema.SchemaURIResolver;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.SchemaFactory;

/**
 * 类名称：CDASchemaValidateTool
 * 类描述：CDA文档schema校验规则工具类
 * 创建人：liuwensheng
 * 创建时间：2017-1-12 上午11:09:24
 * 修改人：liuwensheng
 * 修改时间：2017-1-12 上午11:09:24
 * 修改备注：
 */
public class CDASchemaValidateTool {

    private static Logger LOGGER = Logger.getLogger(Constans.LOG4J_PBS_LOGGER_ID);

    private ICDASchemaValidatorInter schemaValidator;

    /**
     * @param xsdFilePath "resource/sdschemas/PCHIS_CDA.xsd"
     */
    private CDASchemaValidateTool(String xsdFilePath) {
        try {

//        	String serverFilePath = FrameworkServlet.getServerFilePath();
//    		
//    		String filePath = serverFilePath + "/WEB-INF/classes/";
//    		
//    		
//        	FileInputStream xsdFile = null; 
//        	
//        	xsdFile =  new FileInputStream(serverFilePath+xsdFilePath);

//          InputStream xsd = this.getClass().getClassLoader().getResourceAsStream(xsdFilePath);
//          schemaValidator = CDASchemaSAXValidator.newInstance(xsd);

        } catch (Exception e) {
            LOGGER.error(e, e.fillInStackTrace());
            e.printStackTrace();
        }
    }

    /**
     * 根据cda文件的相对路径，读取为document对象
     * 方法名称: readDocument
     *
     * @param cdaFilePath cda文件的相对路径
     * @return
     * @throws DocumentException Document  返回类型说明
     * @author liuwensheng@winning.com.cn<br/>
     * 创建时间：2017-1-12/上午11:17:12<br/>
     */
    private Document readDocument(String cdaFilePath) throws DocumentException {
        Map<String, String> map = new HashMap<String, String>();

        //将xds注册为namesapce的名称
        map.put("xds", "urn:hl7-org:v3");
        map.put("xsi", "urn:hl7-org:v3");

        String serverFilePath = FrameworkServlet.getServerFilePath();

        String filePath = serverFilePath + "/WEB-INF/classes/";

        SAXReader saxReader = new SAXReader();

        saxReader.getDocumentFactory().setXPathNamespaceURIs(map);

        Document resultDocument = null;

        try {
            resultDocument = saxReader.read(new File(filePath + cdaFilePath));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultDocument;
    }

    /**
     * 对生成的CDA文档进行schema规制校验
     * 方法名称: validate
     *
     * @param cdaDoc
     * @param xsdFilePath void  返回类型说明
     * @author liuwensheng@winning.com.cn<br/>
     * 创建时间：2017-1-12/上午11:31:16<br/>
     */
    public static HashMap<String, Object> validateCDA(Document cdaDoc, String xsdFilePath) {


        HashMap<String, Object> yzResult = new HashMap<String, Object>();


        try {

            String serverFilePath = FrameworkServlet.getServerFilePath();

            String filePath = serverFilePath;

            FileInputStream xsdFile = new FileInputStream(filePath + "/" + xsdFilePath);

            LOGGER.info("--> PCHIS_CDA.xsd 文件路径：" + filePath + "/" + xsdFilePath);

            //工具类中的路径 "resource/sdschemas/PCHIS_CDA.xsd"
            ICDASchemaValidatorInter schemaValidator = CDASchemaSAXValidator.newInstance(xsdFile);

            LOGGER.info("--> 工具类中的路径 resource/sdschemas/PCHIS_CDA.xsd");

            //CDASchemaValidateTool test = new CDASchemaValidateTool(filePath+"/"+xsdFilePath);

            //LOGGER.info("-->需要校验的 CDA文档:"+cdaDoc.asXML());

            if (cdaDoc != null) {
                yzResult = schemaValidator.validate(new ByteArrayInputStream(cdaDoc.asXML().getBytes("UTF-8")));
            }


        } catch (Exception e) {
            yzResult.put("YZJG", "AE");
            yzResult.put("YZJGSM", "共享文档格式验证失败，错误原因：" + e.toString());
            e.printStackTrace();
            LOGGER.error(e, e.fillInStackTrace());
        }

        return yzResult;

    }

    public static void validateCDA(String cdaFilePath, String xsdFilePath) {

        try {
            //工具类中的路径 "resource/sdschemas/PCHIS_CDA.xsd"
            CDASchemaValidateTool test = new CDASchemaValidateTool(xsdFilePath);

            //服务器发布环境下的路径 "com/winning/ihe/cda/cdaFiles/Grjbjkxxdj.xml"
            Document xmldoc = test.readDocument(cdaFilePath);

            //Document result = test.schemaValidator.validate(xmldoc);

            Document result = null;
            SchemaSummary summary = new SchemaSummary();
            summary.fromSchemaResultDocument(result);

            if (summary.getErrorCount() > 0) {
                LOGGER.error("共享文档格式验证失败!");
                return;
            }

            LOGGER.info("共享文档格式验证成功!");
        } catch (DocumentException e) {
            e.printStackTrace();
            LOGGER.info("共享文档格式验证失败!");
            LOGGER.error(e.getMessage());
        }
    }
}
